﻿using System;
using System.ComponentModel;
using System.IO;
using UnityEditor;
using UnityEngine;


/// <summary>
/// 输入存储管理
/// </summary>
public class RInputModuleStorage
{
    [Description("默认文件")] private readonly string FileName;
    [Description("存储路径")] private readonly string _SavePath;
    [Description("键值数据")] public DataKeyCollection Collection;


    public event Action<DataKeyCollection> OnStorageLoaded;
    public event Action<DataKeyCollection> OnStorageSaved;

    public RInputModuleStorage()
    {
        this.FileName = "keyMappings.json";
        this._SavePath = Path.Combine(Application.persistentDataPath, this.FileName);
    }


    /// <summary>
    /// 加载
    /// </summary>
    public void Load()
    {
        bool isPathExist = File.Exists(_SavePath);

        if (!isPathExist)
        {
            this.Collection = null;
            return;
        }

        string json = File.ReadAllText(this._SavePath);
        this.Collection = JsonUtility.FromJson<DataKeyCollection>(json);
        OnStorageLoaded?.Invoke(this.Collection);
    }

    /// <summary>
    /// 另存为
    /// </summary>
    public void SaveAs()
    {
        if (Collection == null) return;
        if (string.IsNullOrEmpty(this._SavePath)) return;

        string path = EditorUtility.OpenFolderPanel("选择存储位置", Application.persistentDataPath, $"");

        if (!string.IsNullOrEmpty(path))
        {
            string json = JsonUtility.ToJson(Collection ??= new DataKeyCollection(), true);
            path = Path.Combine(path, this.FileName);

            // 写入
            // 归档
            File.WriteAllText(path, json);
            File.WriteAllText($"{path}/{DateTime.Now:yyyy-MM-dd HH-mm-ss}.copy", json);

            OnStorageSaved?.Invoke(this.Collection);
        }
    }

    /// <summary>
    /// 保存
    /// </summary>
    public void Save()
    {
        if (Collection == null) return;
        if (string.IsNullOrEmpty(this._SavePath)) return;

        if (!string.IsNullOrEmpty(_SavePath))
        {
            string json = JsonUtility.ToJson(Collection, true);

            // 写入
            // 归档
            File.WriteAllText(_SavePath, json);
            File.WriteAllText($"{_SavePath}{DateTime.Now:yyyy-MM-dd HH-mm-ss}.copy", json);

            OnStorageSaved?.Invoke(this.Collection);
        }
    }
}